package com.example.smartagrisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagrisys.common.utils.FileUtil;
import com.example.smartagrisys.entity.Product;
import com.example.smartagrisys.mapper.ProductMapper;
import com.example.smartagrisys.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 产品服务实现类
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private FileUtil fileUtil;

    @Override
    public Page<Product> getProductPage(Page<Product> page, Product product) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (product != null) {
            // 按名称模糊查询
            if (StringUtils.hasText(product.getName())) {
                wrapper.like(Product::getName, product.getName());
            }
            
            // 按类型查询
            if (StringUtils.hasText(product.getType())) {
                wrapper.eq(Product::getType, product.getType());
            }
            
            // 按农户ID查询
            if (product.getFarmerId() != null) {
                wrapper.eq(Product::getFarmerId, product.getFarmerId());
            }
            
            // 按状态查询
            if (product.getStatus() != null) {
                wrapper.eq(Product::getStatus, product.getStatus());
            }
        }
        
        // 默认按创建时间降序排序
        wrapper.orderByDesc(Product::getCreateTime);
        
        return page(page, wrapper);
    }

    @Override
    public List<Product> getProductsByFarmerId(Long farmerId) {
        if (farmerId == null) {
            return null;
        }
        
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getFarmerId, farmerId);
        wrapper.orderByDesc(Product::getCreateTime);
        
        return list(wrapper);
    }

    @Override
    public String uploadProductImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        
        try {
            return fileUtil.uploadFile(file, "product");
        } catch (IOException e) {
            log.error("上传商品图片失败", e);
            return null;
        }
    }

    @Override
    public Product getProductById(Long id) {
        if (id == null) {
            return null;
        }
        
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProduct(Product product) {
        if (product == null) {
            return false;
        }
        
        // 设置初始状态为下架
        product.setStatus(0);
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        
        return save(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProduct(Product product) {
        if (product == null || product.getId() == null) {
            return false;
        }
        
        // 查询原产品信息
        Product oldProduct = getById(product.getId());
        if (oldProduct == null) {
            return false;
        }
        
        // 不修改农户ID和农户名称
        product.setFarmerId(oldProduct.getFarmerId());
        product.setFarmerName(oldProduct.getFarmerName());
        product.setUpdateTime(LocalDateTime.now());
        
        return updateById(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProduct(Long id) {
        if (id == null) {
            return false;
        }
        
        // 查询产品是否存在
        Product product = getById(id);
        if (product == null) {
            return false;
        }
        
        // 删除产品
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean publishProduct(Long id) {
        if (id == null) {
            return false;
        }
        
        // 查询产品是否存在
        Product product = getById(id);
        if (product == null) {
            return false;
        }
        
        // 设置状态为上架
        product.setStatus(1);
        product.setUpdateTime(LocalDateTime.now());
        
        return updateById(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unpublishProduct(Long id) {
        if (id == null) {
            return false;
        }
        
        // 查询产品是否存在
        Product product = getById(id);
        if (product == null) {
            return false;
        }
        
        // 设置状态为下架
        product.setStatus(0);
        product.setUpdateTime(LocalDateTime.now());
        
        return updateById(product);
    }

    @Override
    public List<Product> getAllActiveProducts() {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getStatus, 1)  // 上架状态
               .gt(Product::getStock, 0)   // 有库存
               .orderByDesc(Product::getCreateTime);
        return list(wrapper);
    }
    
    /**
     * 获取农户的所有活跃产品（排除肥料商产品）
     */
    @Override
    public List<Product> getAllActiveFarmerProducts() {
        // 使用自定义Mapper方法，通过联表查询确保只返回角色为farmer的用户的产品
        return baseMapper.selectAllActiveFarmerProducts();
    }
} 